<?php

use LucaDegasperi\OAuth2Server\Authorizer;
use Rootant\Api\Exception\ApiException;
use Rootant\Api\Exception\ValidationException;
use Rootant\Api\Exception\DuplicateOperationException;

class ArticleController extends CommonController
{

    protected $userId = '';
    protected $userIp = '';

    public function __construct(Authorizer $authorizer)
    {
        parent::__construct($authorizer);
        $this->beforeFilter('oauth', ['except' => ['team', 'index', 'report', 'show', 'comment', 'commentList', 'search', 'product', 'anonymousReply', 'moreArticle', 'contact']]);
        $this->beforeFilter('validation');
        $this->afterFilter('disconnect:sqlsrv', ['only' => ['team', 'index', 'report', 'show', 'commentList', 'search', 'contact']]);
        $this->afterFilter('disconnect:thirdly', ['only' => ['product']]);
    }

    private static $_validate = [
        'comment' => [
            'content' => 'required',
        ],
    ];

    public function index()
    {
        $pictureNews = $this->article()
            ->where('article_havelogo', 1)
            ->latest('article_addtime')
            ->take(3)
            ->get();

        foreach ($pictureNews as $value) {
            $value->thumbnail_url = $this->addImagePrefixUrl($value->thumbnail_url);
        }
        // add ad
        if ($firsAd = $this->getFirstAd()) {
            $pictureNews[] = $firsAd;
        }

        $columns = $this->getColumn();

        $otherAds = $this->getOtherAdvertisement(count($columns));

        foreach ($columns as $column) {
            // 获取栏目下的文章列表
            $column->articles = $this->getColumnArticle($column->column_id);
            // add ad
            if ($shift = array_shift($otherAds)) {
                $column->articles[] = $shift;
            }
        }

        return ['picture_news' => $pictureNews, 'article_list' => $columns];
    }

    protected function getFirstAd()
    {
        $firsAd = $this->advertisement()->first();
        if ($firsAd === null) {
            return;
        }
        $firsAd->is_adv = true;

        return $firsAd;
    }

    protected function getOtherAdvertisement($count)
    {
        $ads = $this->advertisement()
            ->skip(1)
            ->take($count)
            ->get();
        foreach ($ads as $ad) {
            $ad->is_adv = true;
        }

        return $ads;
    }

    protected function advertisement()
    {
        return DB::table('advertisement')
            ->select('thumbnail_url', 'url');
    }

    /**
     * 获取栏目下的文章列表
     *
     * @param  string $columnId 栏目id
     * @return array
     */
    protected function getColumnArticle($columnId)
    {
        $articles = $this->getArticlesByColumnId($columnId);

        if (count($articles) === 0) {
            $articles = $this->getArticlesBySubColumnId($columnId);
        }

        return $articles;
    }

    protected function getArticlesBySubColumnId($columnId)
    {
        $columns = $this->column()
            ->where('lanmu_father', $columnId)
            ->get();

        $ids = array();
        foreach ($columns as $column) {
            $ids[] = $column->column_id;
        }

        return $this->article()->whereIn('article_lanmu', $ids)
            ->orderBy('article_addtime', 'desc')
            ->take(3)
            ->get();
    }

    protected function getColumn()
    {
        $columns = $this->dbRepository('sqlsrv', 'lanmu')
            ->select('lanmu_id as column_id', 'lanmu_name as column_name', 'lanmu_father')
            ->where('lanmu_language', 'zh-cn')
            ->whereIn('lanmu_father', [1, 2, 32, 52])
            ->whereNotIn('lanmu_id', [2, 32, 52, 66])
            ->where('lanmu_father', '<>', 32)
            ->get();

        return $this->processColumnData($columns);
    }

    protected function processColumnData($data)
    {
        $data = $this->addSortValue($data);

        $sort = array();
        foreach ($data as $value) {
            $sort[] = $value->sort_value;
        }

        array_multisort($sort, SORT_ASC, $data);

        foreach ($data as $value) {
            unset($value->sort_value);
        }

        return $data;
    }

    protected function addSortValue($data)
    {
        foreach ($data as $value) {
            if ($value->column_id === '6') {
                $value->sort_value = 1;
            } elseif ($value->column_id === '3') {
                $value->sort_value = 3;
            } elseif ($value->column_id === '7') {
                $value->sort_value = 19;
            } elseif ($value->column_id === '2') {
                $value->sort_value = 21;
            } elseif ($value->column_id === '38') {
                $value->sort_value = 15;
            } elseif (in_array($value->column_id, [13, 71, 90, 168, 40, 167, 113, 171])) {
                $value->sort_value = 5;
            } else {
                $value->sort_value = 17;
            }
        }

        return $data;
    }

    protected function filterColumn($data)
    {
        $tmp = array(7, 8, 9, 10, 11, 12);
        return array_filter($data, function($item) use ($tmp)
        {
            return !in_array($item->column_id, $tmp);
        });
    }

    protected function reorder($data)
    {
        foreach ($data as $value) {
            if ($value->column_id === '6') {
                $value->sort_value = 1;
            } elseif ($value->column_id === '3') {
                $value->sort_value = 2;
            } else {
                // default sort value
                $value->sort_value = 3;
            }
        }

        foreach ($data as $value) {
            $sort[] = $value->sort_value;
        }
        array_multisort($sort, SORT_ASC, $data);

        foreach ($data as $value) {
            unset($value->sort_value);
        }

        return $data;
    }

    /**
     * 更多
     * 文章
     *
     * @param string $id 栏目id
     * @return array
     */
    public function moreArticle($id)
    {
        $columns = $this->column()->where('lanmu_father', $id)
            ->get();
        // 没有子栏目信息
        if (count($columns) === 0) {
            return $this->getMoreArticleByColumnId($id);
        }

        foreach ($columns as $column) {
            $column->articles = $this->getArticlesByColumnId($column->column_id);
        }

        return $this->filterArr($columns);
    }

    /**
     * 根据栏目id获得自身更多文章
     *
     * @param  string $id 栏目id
     * @return array
     */
    protected function getMoreArticleByColumnId($id)
    {
        $data = $this->column()
            ->where('lanmu_id', $id)
            ->get();

        foreach ($data as $value) {
            $value->articles = $this->article()
                ->where('article_lanmu', $id)
                ->orderBy('article_addtime', 'desc')
                ->take(20)->get();
        }

        return $data;
    }

    /**
     * 过滤数组，并重新建立数字索引
     *
     * @param  array $array 待处理的数组
     * @return array        返回处理后的数组
     */
    protected function filterArr($array)
    {
        $result = array_filter($array, function($item)
        {
            return !empty($item->articles) || ($item->column_id === '38');
        });

        return array_values($result);
    }

    /**
     * 增加图片前缀
     *
     * @param [type] $thumbnailUrl [description]
     */
    protected function addImagePrefixUrl($thumbnailUrl)
    {
        if (!empty($thumbnailUrl)) {
            return 'http://sisi-smu.org'.str_replace('\\', '/', $thumbnailUrl);
        }

        return '';
    }

    /**
     * 栏目信息固定返回
     *
     * @return object
     */
    protected function column()
    {
        return $this->dbRepository('sqlsrv', 'lanmu')
            ->select('lanmu_id as column_id', 'lanmu_name as column_name')
            ->where('lanmu_language', 'zh-cn')
            ->where('lanmu_active', 1);
    }

    // get 3 articles by column id
    protected function getArticlesByColumnId($id)
    {
        $articles = $this->article()->where('article_lanmu', $id)
            ->orderBy('article_addtime', 'desc')
            ->take(3)
            ->get();

        foreach ($articles as $value) {
            $value->thumbnail_url = $this->addImagePrefixUrl($value->thumbnail_url);
        }

        return $articles;
    }

    /**
     * 报告
     *
     * @return array
     */
    public function report()
    {
        return $this->dbRepository('sqlsrv', 'lanmu')
            ->select('lanmu_id as id', 'lanmu_name as name')
            ->where('lanmu_language', 'zh-cn')
            ->whereIn('lanmu_father', [113, 167, 168])
            ->get();
    }

    /**
     * [getArticle description]
     *
     */
    public function show($id)
    {
        $article = $this->article()
            ->addSelect('article_body as content')
            ->where('article_id', $id)
            ->first();

        if ($article === null) {
            throw new ValidationException('文章 id 参数传递错误');
        }
        // add image prefix
        $article->thumbnail_url = $this->addImagePrefixUrl($article->thumbnail_url);

        $tmp = clone $article;
        unset($tmp->content);
        $this->models['article'] = $tmp;

        $article->is_starred = $this->isStarred($id);

        // 相关文章
        $this->title = $article->title;
        $relatedArticles = $this->getRelatedArticles($id);
        // 热门评论
        $hotComments = $this->getHotComment($id);
        // 处理文章内容里面的图片显示
        $tmpContent = str_replace('&#34;', '"', $article->content);
        $article->content = preg_replace('#(src=")/#', "\$1".'http://sisi-smu.org/', $tmpContent);

        return [
            'article' => $article,
            'related_articles' => $relatedArticles,
            'hot_comments' => $hotComments,
        ];
    }

    /**
     * 检查用户是否收藏文章
     *
     * @param  string $articleId 文章id
     * @return boolean
     */
    protected function isStarred($articleId)
    {
        if (!$this->accessToken) {
            return false;
        }

        $uid = $this->getOwnerId();

        return $this->checkUserStar($uid, $articleId);
    }

    /**
     * 相关文章
     *
     * @param  string $id 文章id
     * @return todo
     */
    protected function getRelatedArticles($id)
    {
        $tag = $this->getTagForRelatedArticle($id);

        if ($tag === '') {
            return [];
        }

        $articles = $this->article()
            ->where('article_title', 'like', "%{$tag}%")
            ->latest('article_addtime')
            ->take(2)
            ->get();

        return $articles;
    }

    protected function getTagForRelatedArticle($id)
    {
        $tmpTag = $this->getTagStr($id);

        return ($tmpTag === '')
            ? $this->getTagForArticle($id)
            : $tmpTag;
    }

    /**
     * 获取文章的热门评论
     *
     * @param  string $articleId 文章id
     * @return todo
     */
    protected function getHotComment($articleId)
    {
        $comments = DB::table('article_comment')
            ->select('id', 'content', 'created_at', 'favours', 'user_id', 'user_ip')
            ->where('article_id', $articleId)
            ->orderBy('favours', 'desc')
            ->take(2)
            ->get();

        $comments = $this->processCommentResponse($comments);

        foreach ($comments as $comment) {
            $comment->article = $this->models['article'];
        }

        return $comments;
    }

    /**
     * 文章评论
     *
     * @param  string $id 文章id
     * @return [type]     [description]
     */
    public function comment($id)
    {
        $this->content = Input::get('content');
        // 提取评论内容的标签
        $this->tagStr = $this->getTagStr($this->content);

        $this->models['comment'] = DB::table('article_comment');

        if ($this->accessToken) {
            $this->uid = $this->authorizer->getResourceOwnerId();

            $insertData = array_merge($this->commentDataIntersection($id), ['user_id' => $this->uid]);

            $this->insertId = $this->models['comment']->insertGetId($insertData);
        } else {
            // 匿名评论文章
            $this->commentAnonymous($id);
        }

        $articleComment = $this->models['comment']
            ->select('id', 'favours', 'content', 'created_at')
            ->find($this->insertId);
        $articleComment->user = $this->getOwner($this->uid, $this->uip);
        $articleComment->flag = self::WEB_FLAG;

        return (array) $articleComment;
    }

    /**
     * 公共数据方法
     *
     * @param  int $articleId
     * @return array
     */
    protected function commentDataIntersection($articleId)
    {
        return array(
                'article_id' => $articleId,
                'content'    => $this->content,
                'tag'        => $this->tagStr,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            );
    }

    /**
     * 匿名评论文章
     *
     * @param  int $articleId
     * @return void
     */
    protected function commentAnonymous($articleId)
    {
        // 校验验证码
        MultiplexController::verifyCaptcha();
        $this->uip = Request::ip();

        $insertData = array_merge($this->commentDataIntersection($articleId), ['user_ip' => $this->uip]);

        $this->insertId = $this->models['comment']->insertGetId($insertData);
    }

    /**
     * 文章评论列表
     *
     * @param  string $id 文章id
     * @return [type]     [description]
     */
    public function commentList($id)
    {
        // 获取文章的信息
        $article = $this->article()->where('article_id', $id)->first();

        $this->models['article_comment'] = DB::table('article_comment');

        $comments = $this->models['article_comment']
            ->select('id', 'content', 'created_at', 'favours', 'user_id', 'user_ip')
            ->where('article_id', $id)
            ->orderBy('created_at', 'desc')
            ->take(4)
            ->get();

        $comments = $this->processCommentResponse($comments);

        foreach ($comments as $comment) {
            $comment->article = $article;
        }
        // extra comments
        $this->title = $article->title;
        $extraComments = $this->getExtraComment($id);

        return [
            'lists'  => $comments,
            'extras' => $extraComments,
        ];
    }

    /**
     * 其他评论
     * 评论互通
     *
     * @param  string $id 文章id
     * @return array
     */
    protected function getExtraComment($id)
    {
        $tag = $this->getTagForExtraComment($id);

        $csi_comment = $this->getCsiComment($tag);
        foreach ($csi_comment as $comment) {
            $comment->article = $this->getCsiArticle($comment->article_id, $comment->image_flag);
        }

        $csp_comment = $this->getCspComment($tag);
        foreach ($csp_comment as $comment) {
            $comment->article = $this->getJournalById($comment->journal_id);
        }

        return array_merge($csi_comment, $csp_comment);
    }

    protected function getTagForExtraComment($id)
    {
        $tmpTag = $this->getTagStr($this->title);

        return ($tmpTag === '')
            ? $this->getTagForComment($id)
            : $tmpTag;
    }

    public function search()
    {
        // 文章查询字符串
        $q = Input::get('q', '');

        $model = $this->article()
            ->where('article_title', 'like', "%{$q}%")
            ->orWhere('article_writer', 'like', "%{$q}%")
            ->orWhere('article_whoadd', 'like', "%{$q}%");
        // 返回数据增加分页
        MultiplexController::addPagination($model);

        return $model->latest('created_at')->get();
    }

    /**
     * 团队
     *
     * @return  array
     */
    public function team()
    {
        $teamModel = $this->dbRepository('sqlsrv', 'expert')
            ->select('expert_id as id', 'expert_photo as avatar_url', 'expert_name as name', 'expert_title as position', 'expert_Description as description')
            ->where('expert_language', 'zh-cn')
            ->whereIn('expert_type', ['领导', '研究人员'])
            ->orderBy('expert_order', 'desc');

        MultiplexController::addPagination($teamModel);

        $members = $teamModel->get();

        foreach ($members as $member) {
            $member->avatar_url = $this->addImagePrefixUrl($member->avatar_url);
        }

        return $members;
    }

    public function product()
    {
        echo $this->dbRepository('thirdly', 'info')
            ->where('info_id', 5)
            ->first()
            ->info_desc_cn;
    }

    /**
     * 收藏文章
     *
     * @param  string $id 文章id
     * @return array
     */
    public function star($id)
    {
        $uid = $this->authorizer->getResourceOwnerId();

        if ($this->checkUserStar($uid, $id)) {
            throw new DuplicateOperationException('您已收藏:(');
        }

        $insertData = array(
                'user_id'    => $uid,
                'article_id' => $id,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            );
        $insertId = $this->models['star']->insertGetId($insertData);

        return (array) $this->models['star']->find($insertId);
    }

    /**
     * 取消收藏文章
     *
     * @param  string $id 文章id
     * @return object
     */
    public function unstar($id)
    {
        $uid = $this->authorizer->getResourceOwnerId();

        DB::table('star')->where('user_id', $uid)
            ->where('article_id', $id)
            ->delete();

        return Response::make('', 204);
    }

    public function contact()
    {
        $contacts = $this->dbRepository('sqlsrv', 'institute')
            ->select('Institute_Name', 'Institute_Logo', 'Institute_LinkMan', 'Institute_Address', 'Institute_PostCode', 'Institute_Tel', 'Institute_Fax', 'Institute_Email')
            ->orderBy('Institute_Order', 'desc')
            ->get();

        foreach ($contacts as $value) {
            $value->Institute_Logo = 'http://sisi-smu.org'.$value->Institute_Logo;
        }

        return $contacts;
    }

}